package cn.caplike.demo.grpc.proto.demo;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * Description: GRPC 服务端.
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2021-12-11 12:35
 */
public class GrpcServer {
    private Server server;

    public static void main(String[] args) throws IOException, InterruptedException {
        final GrpcServer grpcServer = new GrpcServer();

        grpcServer.start();
        grpcServer.await();
    }

    private void start() throws IOException {
        this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl() /* 可以通过 Spring 容器注入 */).build().start();
        System.out.println("Server started!");

        // Async
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("JVM about to shutdown...");
            this.stop();
        }));
    }

    private void stop() {
        if (null != this.server) {
            this.server.shutdown();
        }
    }

     /**
     * 让 server 持续等待, 注意与 thrift 的区别.
     */
    private void await() throws InterruptedException {
        if (null != this.server) {
            this.server.awaitTermination();
        }
    }
}
